#!/bin/sh

die()
{
	echo "$*" >&2
	exit 1
}

# $1=binary $2=sumfile
checksum()
{
	local binary="$1"
	local sumfile="$2"

	"$binary" --check --quiet --status --warn --strict "$sumfile" >/dev/null ||\
		die "One checksum in '$sumfile' FAILED."
}

# $1=basedirectory
check_all_sums()
{
	local basedirectory="$1"

	[ -d "$basedirectory" ] || die "$basedirectory is not a directory"
	find "$basedirectory" \
		-name MD5SUM -o -name MD5SUMS -o \
		-name SHA1SUM -o -name SHA1SUMS -o \
		-name SHA256SUM -o -name SHA256SUMS -o \
		-name SHA512SUM -o -name SHA512SUMS \
		| while read path; do

		echo "Checking '$path'..."
		local dir="$(dirname "$path")"
		local file="$(basename "$path")"
		local prev_dir="$(pwd)"
		cd "$dir" || die "Failed to change directory"
		if [ "$file" = "MD5SUM" -o "$file" = "MD5SUMS" ]; then
			checksum md5sum "$file"
		elif [ "$file" = "SHA1SUM" -o "$file" = "SHA1SUMS" ]; then
			checksum sha1sum "$file"
		elif [ "$file" = "SHA256SUM" -o "$file" = "SHA256SUMS" ]; then
			checksum sha256sum "$file"
		elif [ "$file" = "SHA512SUM" -o "$file" = "SHA512SUMS" ]; then
			checksum sha512sum "$file"
		else
			die "Don't know how to handle '$path'"
		fi
		cd "$prev_dir" || die "Failed to change directory"
	done
}

help()
{
	echo "Usage: check-all-sums DIRECTORY"
}

[ $# -eq 1 ] || {
	help
	exit 1
}
check_all_sums "$1"
exit 0
